<template>
  <gd-row>
    <gd-col :xs="9" :sm="12" :md="12" :lg="7" :xl="5">
      <ClassifyTree
        @scene-tree-current-change="onTreeItemChange"
        :icon="icon"
      ></ClassifyTree>
    </gd-col>
    <gd-col :xs="15" :sm="12" :md="10" :lg="17" :xl="17">
      <gd-row
        :style="{
          height: headerContainerHeight,
          lineHeight: headerContainerHeight,
        }"
      >
        <gd-col :span="4">常用图标组</gd-col>
        <gd-col :span="20">
          <gd-tag
            v-for="(item, idx) in favClassifyNameList"
            :key="item.key"
            style="margin: 5px 10px 5px 0px; cursor: pointer"
            :type="sampleSize(colorTypes, 1)[0]"
            :effect="idx === 0 ? 'dark' : 'plain'"
            @click="onClickFavClassifyItem(item.key, idx)"
          >
            {{ item.label }}
          </gd-tag>
        </gd-col>
      </gd-row>
      <gd-input
        placeholder="搜索图标"
        v-model="searchIconText"
        :style="{ margin: `${searchContainerMarginAligin} 0` }"
      >
        <template #prepend>
          <el-select style="width: 150px" v-model="searchInType">
            <el-option label="当前图标组中搜索" value="cur"></el-option>
            <el-option label="全部分类中搜索" value="all" disabled></el-option>
            <el-option label="常用图标中搜索" value="fav" disabled></el-option>
          </el-select>
        </template>
        <template #append
          ><gd-button @click="onSearch">搜索图标</gd-button></template
        >
      </gd-input>
      <IconGroupCategories
        :curIconGroupCategories="curIconGroupCategories"
        @update:iconGroupAreaHeight="iconGroupAreaHeight = val"
      ></IconGroupCategories>
      <IconItemList
        :curIconItemListPrefix="curIconItemListPrefix"
        :list="iconItemList"
        :pagination="pagination"
        :key="curIconItemListPrefix + iconGroupAreaHeight"
        v-model:curPickedIcon="curPickedIcon"
        :contentHeight="`${475 - iconGroupAreaHeight}px`"
        :filterIconItemIdxList="filterIconItemIdxList"
      ></IconItemList>
    </gd-col>
  </gd-row>
</template>
<script setup>
import { ref, computed } from "vue";
import ClassifyTree from "./classify-tree.vue";
import IconItemList from "./icon-item-list.vue";
import IconGroupCategories from "./icon-group-categories.vue";
import { headerContainerHeight, searchContainerMarginAligin } from "./constant";
import {
  getRandom,
  sampleSize,
  transName,
} from "@gd-accbuild-core/config/utils";
import gdToastService from "@/uni_modules/gd-accbuild-core/components/gd-accbuild-ui/gd-ui/gd-service/gd-toast-service/gd-toast-service";
// #ifdef H5
import * as allBuildInIcons from "@element-plus/icons-vue";
// #endif
const props = defineProps({
  layoutConfig: {
    type: Object,
    default: () => ({
      /**
       * 布局类型
       * "Simple" 简化版没有左树、"Advance" 高级版有左树
       */
      type: "Advance",
      /**
       * 收藏夹分类
       * "build-in"是内置icon: pc的el-icon
       */
      favClassify: ["build-in", "material-symbols"],
      maxFavCacheNum: 5,
    }),
  },
  compatibleApi: {
    type: String,
    default: "https://api.iconify.design/collection",
  },
  icon: {
    type: String,
    default: "",
  },
});
const colorTypes = ["", "info", "success", "danger", "warning"];
const searchInType = ref("cur");
const favClassifyNameList = computed(() => {
  return props.layoutConfig.favClassify.map((el) => {
    if (el === "build-in") {
      return { label: "系统图标", key: el };
    } else {
      return { label: el, key: el };
    }
  });
});
//////////////
const iconGroupAreaHeight = ref(21);
const iconItemList = ref([]);
const curIconItemListPrefix = ref("");
const curIconGroupCategories = ref([]);
const pagination = ref({
  pageNum: 1,
  pageSize: 100,
  totalCount: 0,
});
///////
const searchIconText = ref("");
const filterIconItemIdxList = ref(null);
const onSearch = () => {
  const type = searchInType.value;
  const text = searchIconText.value;
  if (type === "cur") {
    if (!text) {
      filterIconItemIdxList.value = null;
    } else {
      const iconItemListAlias = iconItemList.value;
      filterIconItemIdxList.value = iconItemListAlias
        .filter((el) => el.indexOf(text) !== -1)
        .map((el) => iconItemListAlias.indexOf(el));
    }
  }
  if (Array.isArray(filterIconItemIdxList.value)) {
    pagination.value.totalCount = filterIconItemIdxList.value.length;
  } else {
    pagination.value.totalCount = iconItemList.value.length;
  }
};
const _emits = defineEmits(["update:layoutConfig", "update:icon"]);
const curPickedIcon = computed({
  get() {
    return props.icon;
  },
  set(val) {
    _emits("update:icon", val);
  },
});
const clearIconCache = () => {
  for (let i = 0; i < localStorage.length; i++) {
    let key = localStorage.key(i);
    if (/^iconify[0-9]*$/.test(key)) {
      localStorage.removeItem(key);
    }
  }
  localStorage.setItem("iconify-count", "0");
};
const onTreeItemChangeSetVal = (node, res) => {
  //_emits("update:icon", "");
  clearIconCache();
  curIconItemListPrefix.value =
    node.data.id === "build-in" ? "" : node.data.prefix;

  pagination.value = {
    totalCount: +res.data.total,
    pageNum: 1,
    pageSize: 100,
  };
  /* const favClassify =
    props.layoutConfig.favClassify.length === props.layoutConfig.maxFavCacheNum
      ? props.layoutConfig.favClassify.slice(0, -1)
      : props.layoutConfig.favClassify;
  if (!favClassify.includes(node.data.id)) {
    favClassify.splice(0, 0, node.data.id);
  }
  props.layoutConfig.favClassify = favClassify;
  _emits("update:layoutConfig", { ...props.layoutConfig, favClassify }); */
  if (res.data.hasOwnProperty("uncategorized")) {
    iconItemList.value = Object.values(res.data.uncategorized);
    curIconGroupCategories.value = [];
  } else if (res.data.hasOwnProperty("categories")) {
    const allCategories = Object.keys(res.data.categories);
    const r = [];
    allCategories.forEach((k) => {
      r.push(...res.data.categories[k]);
    });
    iconItemList.value = r;
    curIconGroupCategories.value = allCategories;
  }
};
const allBuildInIconKeys = Object.keys(allBuildInIcons).map((key) => {
  return transName(key, "Pascal", "Kebab");
});
const moveIconCategories = (item) => {
  const idx = props.layoutConfig.favClassify.findIndex((el) => el === item);
  if (idx !== -1) {
    props.layoutConfig.favClassify.splice(idx, 1);
  }
  if (
    props.layoutConfig.favClassify.length === props.layoutConfig.maxFavCacheNum
  ) {
    props.layoutConfig.favClassify.pop();
  }
  props.layoutConfig.favClassify.unshift(item);
};
const onTreeItemChange = (node) => {
  if (node.data.id === curIconItemListPrefix.value) return;
  moveIconCategories(node.data.id);
  if (node.data.id === "build-in") {
    const mockRes = {
      data: {
        uncategorized: allBuildInIconKeys,
        total: allBuildInIconKeys.length,
      },
    };
    onTreeItemChangeSetVal(node, mockRes);
    return;
  }
  if (node.data.parentId) {
    const url = `${props.compatibleApi}?prefix=${node.data.prefix}&info=true&chars=true&aliases=true`;
    uni
      .request({
        method: "GET",
        url: url,
        header: {},
      })
      .then((res) => {
        if (res.errMsg !== "request:ok") {
          gdToastService({
            type: "error",
            message: "icon列表获取失败",
          });
          return;
        }
        onTreeItemChangeSetVal(node, res);
      });
  }
};

const onClickFavClassifyItem = (item, idx) => {
  onTreeItemChange({
    data: {
      parentId: "xxx",
      prefix: item,
      id: item,
    },
  });
};
console.log('主按钮picker开始')
</script>
